﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using XiAnAirport.DAL;
using XiAnAirport.ElevatorWebSocket;
using XiAnAirport.Models;

namespace XiAnAirport.BUS
{
    public class RepairWorkOrderBUS
    {
        public ResponseMessage AddWorkOrder(RepairWorkOrderInfo workorderinfo)
        {
            RepairWorkOrderDAL da = new RepairWorkOrderDAL();
            ResponseMessage message = new ResponseMessage();
            try
            {
                string result = da.AddWorkOrder(workorderinfo);
                if (result == "success")
                {
                    //InitRepairtime(workorderinfo.elevatorId);
                    InitWorkOrder();
                    UpdateElevatorState(workorderinfo.elevatorId);
                    message.errcode = 0;
                    message.errmsg = "";
                    message.data = null;
                    message.total = 0;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = result;
                    message.data = null;
                    message.total = 0;
                }

            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "新增维修工单";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("新增维修工单" + e.ToString());
            }
            return message;
        }

        public void InitRepairtime(int id)
        {
            try
            {
                if (ElevatorStateBUS.device_list != null)
                {
                    ElevatorAreaDAL da = new ElevatorAreaDAL();
                    if (id > 0)
                    {
                        int dataid = ElevatorStateBUS.device_list.FindIndex(x => x.id == id);
                        if (dataid > -1)
                        {
                            Elevator elevator1 = ElevatorStateBUS.device_list[dataid];
                            elevator1.faultnum = da.QueryElevatorFault(elevator1.id);
                            ElevatorStateBUS.device_list[dataid] = elevator1;
                        }
                    }
                }
            }
            catch
            {

            }
        }

        public string GetWorkNo()
        {
            while (true)
            {
                Random rd = new Random();
                int num = rd.Next(1, 9999);
                string orderNO = DateTime.Now.ToString("yyMMdd") + num.ToString().PadLeft(4, '0');
                if (CheckWorkNo(orderNO))
                {
                    return orderNO;
                }
            }
        }

        public bool CheckWorkNo(string orderNO)
        {
            RepairWorkOrderDAL repairWorkOrderDAL = new RepairWorkOrderDAL();
            try
            {
                string number = repairWorkOrderDAL.CheckWorkNo(orderNO);
                if (string.IsNullOrEmpty(number))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        public ResponseMessage EditWorkOrder(RepairWorkOrderInfo workorderinfo)
        {
            RepairWorkOrderDAL da = new RepairWorkOrderDAL();
            ResponseMessage message = new ResponseMessage();
            try
            {
                string result = da.EditWorkOrder(workorderinfo);

                if (result.Contains("success"))
                {
                    //InitRepairtime(workorderinfo.elevatorId);
                    InitWorkOrder();
                    UpdateElevatorState(workorderinfo.elevatorId);
                    message.errcode = 0;
                    message.errmsg = "";
                    message.data = null;
                    message.total = 1;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = result;
                    message.data = null;
                    message.total = 0;
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "修改维修工单";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("修改维修工单" + e.ToString());
            }
            return message;
        }

        public ResponseMessage QueryAllRepairman()
        {
            ResponseMessage message = new ResponseMessage();

            RepairWorkOrderDAL da = new RepairWorkOrderDAL();
            List<UserInfo> content = da.QueryAllRepairman();

            message.errcode = 0;
            message.errmsg = "";
            message.data = content;

            return message;
        }

        public ResponseMessage DelWorkOrder(RepairWorkOrderInfo workorderinfo)
        {
            RepairWorkOrderDAL da = new RepairWorkOrderDAL();
            string result = string.Empty;
            ResponseMessage message = new ResponseMessage();
            try
            {
                result = da.DelWorkOrder(workorderinfo.id);

                if (result.Contains("success"))
                {
                    InitWorkOrder();
                    //InitRepairtime(workorderinfo.elevatorId);
                    message.errcode = 0;
                    message.errmsg = "";
                    message.data = null;
                    message.total = 1;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = result;
                    message.data = null;
                    message.total = 0;
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "删除维修工单";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("删除维修工单" + e.ToString());
            }
            return message; ;
        }

        public ResponseMessage LoadWorkOrder(int orderid)
        {
            ResponseMessage message = new ResponseMessage();
            InspectionPlanDAL inspectionPlanDAL = new InspectionPlanDAL();
            RepairWorkOrderDAL da = new RepairWorkOrderDAL();
            try
            {
                RepairWorkOrderInfo content = da.LoadWorkOrder(orderid);
                if (content != null)
                {
                    if (!string.IsNullOrEmpty(content.preparationTime))
                    {
                        content.preparationTime = Convert.ToDateTime(content.preparationTime).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    if (!string.IsNullOrEmpty(content.receiveTime))
                    {
                        content.receiveTime = Convert.ToDateTime(content.receiveTime).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    if (!string.IsNullOrEmpty(content.arriveTime))
                    {
                        content.arriveTime = Convert.ToDateTime(content.arriveTime).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    if (!string.IsNullOrEmpty(content.completeTime))
                    {
                        content.completeTime = Convert.ToDateTime(content.completeTime).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    if (!string.IsNullOrEmpty(content.acceptanceTime))
                    {
                        content.acceptanceTime = Convert.ToDateTime(content.acceptanceTime).ToString("yyyy-MM-dd HH:mm:ss");
                    }

                    message.errcode = 0;
                    message.errmsg = "";
                    message.data = content;
                    message.total = 1;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "载入工单信息失败";
                    message.data = null;
                    message.total = 0;
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "载入维修工单";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("载入维修工单" + e.ToString());
            }
            return message;
        }

        public ResponseMessage QueryWorkOrder(RepairWorkOrderInfo orderinfo)
        {
            ResponseMessage message = new ResponseMessage();
            RepairWorkOrderDAL da = new RepairWorkOrderDAL();
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                mqttDataDAL.DeleteDistinctRepairWorkorder();
                List<RepairWorkOrderInfo> content = da.QueryWorkOrder(orderinfo);
                message.errcode = 0;
                message.errmsg = "";
                message.data = content;
                message.total = da.QueryWorkOrderCount(orderinfo);
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "查询维修工单";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("查询维修工单" + e.ToString());
            }
            return message;
        }

        public ResponseMessage QueryWorkOrderHistory(RepairWorkOrderInfo orderinfo)
        {
            ResponseMessage message = new ResponseMessage();
            RepairWorkOrderDAL da = new RepairWorkOrderDAL();
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                mqttDataDAL.DeleteDistinctRepairWorkorder();
                List<RepairWorkOrderInfo> content = da.QueryWorkOrderHistory(orderinfo);

                message.errcode = 0;
                message.errmsg = "";
                message.data = content;
                message.total = da.QueryWorkOrderHistoryCount(orderinfo);
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "查询维修历史工单";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("查询维修历史工单" + e.ToString());
            }
            return message;
        }

        public ResponseMessage QueryFaultHistory(FaultReportInfo faultReport)
        {
            ResponseMessage message = new ResponseMessage();
            RepairWorkOrderDAL da = new RepairWorkOrderDAL();
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                mqttDataDAL.DeleteDistinctFaultReport();
                List<FaultReportInfo> content = da.QueryFaultHistory(faultReport);
                message.errcode = 0;
                message.errmsg = "";
                message.data = content;
                message.total = da.QueryFaultHistoryCount(faultReport);
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "查询故障历史";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("查询故障历史" + e.ToString());
            }
            return message;
        }

        public ResponseMessage ExportRepair(RepairWorkOrderInfo repairWorkOrderInfo, string path)
        {
            ResponseMessage response = new ResponseMessage();
            try
            {
                RepairWorkOrderDAL repairWorkOrderDAL = new RepairWorkOrderDAL();
                List<RepairWorkOrderInfo> list = repairWorkOrderDAL.QueryWorkOrder(repairWorkOrderInfo);
                if (list.Count < 65536)
                {
                    string sFileName = "维修工单.xlsx";

                    FileInfo file = new FileInfo(Path.Combine(path, sFileName));

                    file.Delete();
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    using (ExcelPackage package = new ExcelPackage(file))

                    {
                        // 添加worksheet

                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("维修工单");

                        //添加头
                        worksheet.Cells[1, 1].Value = "工单编号";
                        worksheet.Cells[1, 2].Value = "电梯名称";
                        worksheet.Cells[1, 3].Value = "工单创建日期";
                        worksheet.Cells[1, 4].Value = "故障描述";
                        worksheet.Cells[1, 5].Value = "工单类型";
                        worksheet.Cells[1, 6].Value = "工单状态";

                        //添加值

                        for (int i = 0; i < list.Count; i++)
                        {
                            RepairWorkOrderInfo repairWorkOrder = list[0];
                            worksheet.Cells[i + 2, 1].Value = repairWorkOrder.workorderNO;
                            worksheet.Cells[i + 2, 2].Value = repairWorkOrder.elevatorName;
                            worksheet.Cells[i + 2, 3].Value = Convert.ToDateTime(repairWorkOrder.preparationTime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 4].Value = repairWorkOrder.faultCause;
                            worksheet.Cells[i + 2, 5].Value = repairWorkOrder.workordeType == 0 ? "一般性" : "紧急性";
                            worksheet.Cells[i + 2, 6].Value = repairWorkOrder.workorderStateName;
                        }
                        package.Save();

                    }
                    response.errcode = 0;
                    response.errmsg = "";
                    response.data = "/" + sFileName;
                }
                else
                {
                    response.errcode = 1;
                    response.errmsg = "数据量超过65535条，无法导出";
                }

            }
            catch (Exception ex)
            {
                response.errcode = 1;
                response.errmsg = "导出失败";
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "导出维修工单";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("导出维修工单" + ex.ToString());
            }
            return response;
        }

        public ResponseMessage GenerateRepairWorkOrderNo()
        {
            ResponseMessage message = new ResponseMessage();
            string workorder = GetWorkNo();
            message.data = workorder;
            return message;
        }

        public ResponseMessage ExportFaultHistroy(FaultReportInfo faultReport, string path)
        {
            ResponseMessage response = new ResponseMessage();
            try
            {
                RepairWorkOrderDAL repairWorkOrderDAL = new RepairWorkOrderDAL();
                List<FaultReportInfo> list = new List<FaultReportInfo>();
                if (string.IsNullOrEmpty(faultReport.ids))
                {
                    list = repairWorkOrderDAL.QueryFaultHistory(faultReport);
                }
                else
                {
                    list = repairWorkOrderDAL.QueryFaultHistoryByIds(faultReport);
                }
                if (list.Count < 65536)
                {
                    string sFileName = "故障历史.xlsx";

                    FileInfo file = new FileInfo(Path.Combine(path, sFileName));

                    file.Delete();
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    using (ExcelPackage package = new ExcelPackage(file))

                    {
                        // 添加worksheet

                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("故障历史");

                        //添加头
                        worksheet.Cells[1, 1].Value = "设备名称";
                        worksheet.Cells[1, 2].Value = "设备编号";
                        worksheet.Cells[1, 3].Value = "设备位置";
                        worksheet.Cells[1, 4].Value = "故障来源";
                        worksheet.Cells[1, 5].Value = "故障原因";
                        worksheet.Cells[1, 6].Value = "故障开始时间";
                        worksheet.Cells[1, 7].Value = "故障结束时间";

                        //添加值

                        for (int i = 0; i < list.Count; i++)
                        {
                            FaultReportInfo repairWorkOrder = list[i];
                            worksheet.Cells[i + 2, 1].Value = repairWorkOrder.elevatorName;
                            worksheet.Cells[i + 2, 2].Value = repairWorkOrder.elevatorNo;
                            worksheet.Cells[i + 2, 3].Value = repairWorkOrder.mainAreaName + "-" + repairWorkOrder.areaName;
                            worksheet.Cells[i + 2, 4].Value = repairWorkOrder.faultSource;
                            worksheet.Cells[i + 2, 5].Value = repairWorkOrder.faultCode;
                            worksheet.Cells[i + 2, 6].Value = repairWorkOrder.faultTime == null ? "" : Convert.ToDateTime(repairWorkOrder.faultTime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 7].Value = repairWorkOrder.faultEndTime == null ? "" : Convert.ToDateTime(repairWorkOrder.faultEndTime).ToString("yyyy/MM/dd HH:mm:ss");
                        }
                        package.Save();

                    }
                    response.errcode = 0;
                    response.errmsg = "";
                    response.data = "/" + sFileName;
                }
                else
                {
                    response.errcode = 1;
                    response.errmsg = "数据量超过65535条，无法导出";
                }

            }
            catch (Exception ex)
            {
                response.errcode = 1;
                response.errmsg = "导出失败";
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "导出故障历史";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("导出故障历史" + ex.ToString());
            }
            return response;
        }

        public ResponseMessage ExportRepairHistory(RepairWorkOrderInfo repairWorkOrderInfo, string path)
        {
            ResponseMessage response = new ResponseMessage();
            try
            {
                RepairWorkOrderDAL repairWorkOrderDAL = new RepairWorkOrderDAL();
                List<RepairWorkOrderInfo> list = new List<RepairWorkOrderInfo>();
                if (!string.IsNullOrEmpty(repairWorkOrderInfo.ids))
                {
                    list = repairWorkOrderDAL.QueryWorkOrderHistoryByIds(repairWorkOrderInfo);
                }
                else
                {
                    if (repairWorkOrderInfo.type == 0)//工单
                    {
                        list = repairWorkOrderDAL.QueryWorkOrder(repairWorkOrderInfo);
                    }
                    else//历史记录
                    {
                        list = repairWorkOrderDAL.QueryWorkOrderHistory(repairWorkOrderInfo);
                    }
                }

                if (list.Count < 65536)
                {
                    string sFileName = "维修工单.xlsx";

                    FileInfo file = new FileInfo(Path.Combine(path, sFileName));

                    file.Delete();
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    using (ExcelPackage package = new ExcelPackage(file))

                    {
                        // 添加worksheet

                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("维修工单");

                        //添加头
                        worksheet.Cells[1, 1].Value = "工单编号";
                        worksheet.Cells[1, 2].Value = "设备名称";
                        worksheet.Cells[1, 3].Value = "设备编号";
                        worksheet.Cells[1, 4].Value = "设备位置";
                        worksheet.Cells[1, 5].Value = "工单类型";
                        worksheet.Cells[1, 6].Value = "报修人";
                        worksheet.Cells[1, 7].Value = "报修电话";
                        worksheet.Cells[1, 8].Value = "报修时间";
                        worksheet.Cells[1, 9].Value = "故障描述";
                        worksheet.Cells[1, 10].Value = "维保员";
                        worksheet.Cells[1, 11].Value = "维保员工号";
                        worksheet.Cells[1, 12].Value = "维保员电话";
                        worksheet.Cells[1, 13].Value = "维修时间";
                        worksheet.Cells[1, 14].Value = "维修结果";
                        worksheet.Cells[1, 15].Value = "故障原因";
                        worksheet.Cells[1, 16].Value = "工单状态";
                        worksheet.Cells[1, 17].Value = "制单时间";
                        worksheet.Cells[1, 18].Value = "接收时间";
                        worksheet.Cells[1, 19].Value = "到达时间";
                        worksheet.Cells[1, 20].Value = "完成时间";
                        worksheet.Cells[1, 21].Value = "验收时间";
                        //添加值

                        for (int i = 0; i < list.Count; i++)
                        {
                            RepairWorkOrderInfo repairWorkOrder = list[i];
                            worksheet.Cells[i + 2, 1].Value = repairWorkOrder.workorderNO;
                            worksheet.Cells[i + 2, 2].Value = repairWorkOrder.elevatorName;
                            worksheet.Cells[i + 2, 3].Value = repairWorkOrder.elevatorNO;
                            worksheet.Cells[i + 2, 4].Value = repairWorkOrder.mainAreaName + "-" + repairWorkOrder.areaName;
                            worksheet.Cells[i + 2, 5].Value = repairWorkOrder.workordeType == 0 ? "一般性" : "紧急性";
                            worksheet.Cells[i + 2, 6].Value = repairWorkOrder.reportPerson;
                            worksheet.Cells[i + 2, 7].Value = repairWorkOrder.reportPhone;
                            worksheet.Cells[i + 2, 8].Value = repairWorkOrder.reportTime == null ? "" : Convert.ToDateTime(repairWorkOrder.reportTime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 9].Value = repairWorkOrder.faultCause;
                            worksheet.Cells[i + 2, 10].Value = repairWorkOrder.receiver;
                            worksheet.Cells[i + 2, 11].Value = repairWorkOrder.receiverNo;
                            worksheet.Cells[i + 2, 12].Value = repairWorkOrder.receiverPhone;
                            worksheet.Cells[i + 2, 13].Value = repairWorkOrder.maintenanceTime == null ? "" : Convert.ToDateTime(repairWorkOrder.maintenanceTime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 14].Value = repairWorkOrder.repair_information;
                            worksheet.Cells[i + 2, 15].Value = repairWorkOrder.faultReason;
                            worksheet.Cells[i + 2, 16].Value = repairWorkOrder.workorderStateName;
                            worksheet.Cells[i + 2, 17].Value = repairWorkOrder.preparationTime == null ? "" : Convert.ToDateTime(repairWorkOrder.preparationTime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 18].Value = repairWorkOrder.receiveTime == null ? "" : Convert.ToDateTime(repairWorkOrder.receiveTime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 19].Value = repairWorkOrder.arriveTime == null ? "" : Convert.ToDateTime(repairWorkOrder.arriveTime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 20].Value = repairWorkOrder.completeTime == null ? "" : Convert.ToDateTime(repairWorkOrder.completeTime).ToString("yyyy/MM/dd HH:mm:ss");
                            worksheet.Cells[i + 2, 21].Value = repairWorkOrder.acceptanceTime == null ? "" : Convert.ToDateTime(repairWorkOrder.acceptanceTime).ToString("yyyy/MM/dd HH:mm:ss");
                        }
                        package.Save();

                    }
                    response.errcode = 0;
                    response.errmsg = "";
                    response.data = "/" + sFileName;
                }
                else
                {
                    response.errcode = 1;
                    response.errmsg = "数据量超过65535条，无法导出";
                }

            }
            catch (Exception ex)
            {
                response.errcode = 1;
                response.errmsg = "导出失败";
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "导出维修历史";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("导出维修历史" + ex.ToString());
            }
            return response;
        }

        public ResponseMessage BatchDelWorkOrder(string ids)
        {
            RepairWorkOrderDAL da = new RepairWorkOrderDAL();
            string result = string.Empty;
            ResponseMessage message = new ResponseMessage();
            try
            {
                result = da.BatchDelWorkOrder(ids);

                if (result.Contains("success"))
                {
                    message.errcode = 0;
                    message.errmsg = "";
                    message.data = null;
                    message.total = 1;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = result;
                    message.data = null;
                    message.total = 0;
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "批量删除维修工单";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("批量删除维修工单" + e.ToString());
            }
            return message; ;
        }

        public ResponseMessage QueryFaultByElevatorIds(Elevator elevator)
        {
            ResponseMessage message = new ResponseMessage();
            RepairWorkOrderDAL da = new RepairWorkOrderDAL();
            try
            {
                List<FaultReportInfo> content = da.QueryFaultByElevatorIds(elevator);
                message.errcode = 0;
                message.errmsg = "";
                message.data = content;
                message.total = da.QueryFaultByElevatorIdsCount(elevator);
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = null;
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "查询电梯故障";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("查询电梯故障" + e.ToString());
            }
            return message;
        }

        public static void InitWorkOrder()
        {
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                int maintenance = 0;
                for (int i = 0; i < 2; i++)
                {
                    try
                    {
                        string type = string.Empty;
                        int datanum = 0;

                        mqttdata mqttdata = new mqttdata();

                        if (i == 0)
                        {
                            type = "faultTotal";
                            List<mqttdata> list = mqttDataDAL.QueryMqttdata("OrderIncomplete", "04", "KONE");
                            //int old_value = list.FirstOrDefault(x => x.dataType == "maintain").dataNum + list.FirstOrDefault(x => x.dataType == "repair").dataNum;
                            //datanum = old_value + mqttDataDAL.QueryMaintainOrder() + mqttDataDAL.QueryRepairOrder();
                            int old_value = (int)list.FirstOrDefault(x => x.dataType == "repair").dataNum;
                            datanum = old_value + mqttDataDAL.QueryRepairOrder();
                            maintenance = datanum;
                        }
                        else if (i == 1)
                        {
                            type = "faultCompleted";
                            datanum = maintenance - mqttDataDAL.QueryInCompletelRepairOrder();
                        }

                        mqttdata.dataNum = datanum;
                        mqttdata.manufacturer = "KONE";
                        mqttdata.manufacturerId = "04";
                        mqttdata.topicType = "TodayProcess";
                        mqttdata.dataType = type;
                        bool result = mqttDataDAL.CheckData(mqttdata.manufacturer, mqttdata.manufacturerId, type, mqttdata.topicType);

                        if (result)
                        {
                            mqttDataDAL.UpdateMqttData(mqttdata);
                        }
                        else
                        {
                            mqttDataDAL.AddMqttData(mqttdata);
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
                bool result_5 = PushNoticeMessage("Refresh").Result;
                bool result_6 = PushKoneHomeMessage("RefreshHomePage").Result;
            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "初始化工单数量";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("初始化工单数量" + e.ToString());
            }
        }

        public static async Task<bool> PushNoticeMessage(string message)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushNoticeMessage(message);
        }

        public static async Task<bool> PushKoneHomeMessage(string message)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushKoneHomeMessage(message);
        }

        public void UpdateElevatorState(int elevatorid)
        {
            try
            {
                List<LiftStateALL> list = ElevatorStateBUS.state_list;
                ElevatorAreaDAL elevatorAreaDAL = new ElevatorAreaDAL();
                Elevator elevator = elevatorAreaDAL.LoadElevator(elevatorid);
                int ele_index = list.FindIndex(x => x.opcNO == elevator.opcNO);
                if (ele_index > -1)
                {
                    LiftStateALL liftStateALL = list[ele_index];
                    liftStateALL.maintenanceTime = elevatorAreaDAL.QuerylastRepairTime(elevator.id);
                    bool result = PushSingleElevatorMessage(elevator.id, liftStateALL).Result;
                }

                //Dictionary<string, LiftStateALL> list = ElevatorStateBUS._dic;
                //LiftStateALL liftStateALL = new LiftStateALL();
                //ElevatorAreaDAL elevatorAreaDAL = new ElevatorAreaDAL();
                //Elevator elevator = elevatorAreaDAL.LoadElevator(elevatorid);
                //if (list != null)
                //{
                //    if (list.TryGetValue(elevator.opcNO, out liftStateALL))
                //    {
                //        liftStateALL.maintenanceTime = elevatorAreaDAL.QuerylastRepairTime(elevator.id);
                //        bool result = PushSingleElevatorMessage(elevator.id, liftStateALL).Result;
                //    }
                //}
            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "更新电梯状态";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("更新电梯状态" + e.ToString());
            }
        }

        public async Task<bool> PushSingleElevatorMessage(int elevatorid, LiftStateALL liftStateALL)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushElevatorMessage(elevatorid, liftStateALL);
        }
    }
}
